package linkedlist;



public class TwoWayLinkedListDemo {
    public static void main(String[] args) {
        TwoWayLinkedList list= new TwoWayLinkedList();
        BookNode bookNode1 = new BookNode(1,"安徒生童话");
        BookNode bookNode2= new BookNode(2,"美人鱼");
        BookNode bookNode3 = new BookNode(3,"一千零一夜");
        BookNode bookNode4 = new BookNode(4,"一千零二夜");
        list.addbyorder(bookNode3);
        list.addbyorder(bookNode1);
        list.addbyorder(bookNode2);
        System.out.println("删除前---------------");
        list.show();
        System.out.println("删除后---------------");
        list.del(bookNode4);
        list.show();
    }
}
class TwoWayLinkedList{
    private BookNode head=new BookNode(0,"头结点");
    public void addbyorder(BookNode node){
        BookNode temp=head;
        while(temp.next!=null){
            if (temp.no>node.no)
                break;
            temp=temp.next;
        }
        if (temp.no>node.no){
            temp.pre.next=node;
            node.pre=temp.pre;
            node.next=temp;
            temp.pre=node;
        }else{//没有找到比插入节点更大的节点,所以将节点插入到最后
            temp.next=node;
            node.next=null;
            node.pre=temp;
        }
    }
    public void del(BookNode node){
        BookNode temp=head;
        if (temp.next==null){
            System.out.println("链表为空,无法删除");
            return;
        }
        temp=temp.next;
        while(temp!=null){
            if (node.no==temp.no)
                break;
            temp=temp.next;
        }
        if (temp==null){
            System.out.println("找不到要删除的节点,请核对后在删除");
        }else{
            temp.pre.next=temp.next;
            temp.next.pre=temp.pre;
        }
    }
    public void show(){
        BookNode temp=head;
        do {
            temp=temp.next;
            System.out.println(temp);
        }while(temp.next!=null);
    }

}
class BookNode{
    public int no;
    public String bookName;
    public BookNode next;
    public BookNode pre;

    public BookNode(int no, String bookName) {
        this.no = no;
        this.bookName = bookName;
    }

    @Override
    public String toString() {
        return "BookNode{" +
                "no=" + no +
                ", bookName='" + bookName + '\'' +
                '}';
    }
}
